/* eslint-disable @typescript-eslint/no-non-null-assertion */
import type { DictApi } from '../dict';

import { requestClient } from '#/api/request';

type DataSource<T = any> = string | T[];

/**
 * 通用数据转换函数，支持API响应和本地数组转换
 * @param source 数据源，可以是API地址或对象数组
 * @param labelField 标签字段名
 * @param valueField 值字段名
 * @returns SelectOption数组
 */
export const getSelectOptions = async <T extends Record<string, any>>(
  source: DataSource<T>,
  labelField: string,
  valueField: string,
): Promise<
  Record<'options' | 'oriData', DictApi.SelectOption[] | Record<string, any>>
> => {
  if (typeof source === 'string') {
    const res = await requestClient.get(source);
    if (!res.data) return { options: [], oriData: {} };
    const opt = res.data.map((item: any) => ({
      label: item[labelField],
      value: item[valueField],
    }));
    return { options: opt, oriData: res.data };
  }

  const opt = source.map((item) => ({
    label: item[labelField],
    value: item[valueField],
  }));
  return { options: opt, oriData: source };
};

/**
 * 通用数据映射函数，根据字段数量返回不同结构
 * @param data 对象数组
 * @param keyField 键字段名
 * @param valueFields 值字段名数组
 * @returns 根据valueFields长度返回不同结构的映射对象
 */
export const useFieldMap = <T extends Record<string, any>>(
  data: T[],
  keyField: string,
  valueFields: string[],
): Record<string, any> => {
  return data?.reduce(
    (acc, item) => {
      const key = item[keyField];

      acc[key] =
        valueFields.length === 1
          ? item[valueFields[0]!]
          : valueFields?.reduce(
              (valAcc, field) => {
                valAcc[field] = item[field];
                return valAcc;
              },
              {} as Record<string, any>,
            );

      return acc;
    },
    {} as Record<string, any>,
  );
};
